<template>
  <div class="fieldTemplateDetail-container">
    <section class="top">
      <div class="title">
        <PmBreadcrumb />
        <span style="font-weight: 400; font-size: 18px; line-height: 22px"
          >自定义字段模板</span
        >
        <el-icon size="10" style="margin: 0 6px"><ArrowRight /></el-icon>
        <span>{{ route.query.name }}</span>
      </div>
      <div style="display: flex; gap: 12px">
        <el-input placeholder="请输入" />
        <el-button @click="handleAdd" type="primary" :icon="Plus"
          >添加字段</el-button
        >
      </div>
    </section>
    <div class="content">
      <div class="alert">
        项目字段用于配置项目详情需要的显示字段，支持配置多种业务字段类型，以及自定义字段排序，配置后对后续使用该项目类型的项目生效。
      </div>
      <div class="wbs-tree-container">
        <!--   表格   -->
        <CLTable
          v-loading="loading"
          :router-fields="['invisibleStatus']"
          :fields="fields"
          :initial-data="tableData"
          :line-height="currentLineHeight"
          :more-actions="moreActions"
          :tableConfig="tableConfig"
          @onMoreAction="handleMoreAction"
        >
        </CLTable>
        <!-- 字段配置悬浮层 -->
        <FieldConfigPopup
          :fields="currentFields"
          :position="fieldConfigPosition"
          :visible="showFieldConfig"
          @close="showFieldConfig = false"
          @fieldsChange="handleFieldsChange"
        />
      </div>
    </div>
    <AddFieldDialog
      v-model="dialogVisible"
      :title="operate === 'create' ? '添加字段' : '修改字段'"
      @handleSubmit="handleCreateOrEdit"
      :originData="selectedNode"
    />
  </div>
</template>

<script setup lang="ts">
  import { useRoute } from "vue-router";
  import { ArrowRight, Plus } from "@element-plus/icons-vue";
  import PmBreadcrumb from "@/components/PmBreadcrumb.vue";
  import {
    detailTemplate,
    updateTemplate,
  } from "@/api/pm/customFieldTemplate.ts";
  import { dialogFields, tableFields } from "./fields/index.ts";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import { ref, provide, onMounted } from "vue";
  import {
    type BaseDataConfigEntityRes,
    type baseFieldVo,
    TargetType,
  } from "@/interface/pm/baseFieldManagement.ts";
  import { deepCopy } from "@/utils/common.ts";
  import { ElMessage, ElMessageBox } from "element-plus";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import AddFieldDialog from "@/views/pm/setting/baseInfo/AddFieldDialog.vue";
  import type { ColumnDefinedTemplateEntityRes } from "@/interface/pm/customFieldTemplate.ts";
  import dist from "@/utils/dist.ts";
  import { updateBaseField } from "@/api/pm/baseFieldManagement.ts";

  const route = useRoute();
  const templateDetails = ref<ColumnDefinedTemplateEntityRes>({});

  const dialogVisible = ref(false);
  const operate = ref("create");
  const loading = ref(false);
  const fields = ref<DynamicField[]>(tableFields);
  const tableData = ref<baseFieldVo[]>([]);
  const tableDataOrigin = ref<baseFieldVo[]>([]);
  const selectedNode = ref<baseFieldVo>({} as baseFieldVo);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );
  const moreActions = ref([
    // { key: "setting", label: "配置类型" },
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
  ]);
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 120px)",
    showOperationsColumn: true, // 是否显示操作列
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 10, //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: false,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    rowSeriesNumber: {
      dragOrder: true, // 开启行号拖拽排序
    },
    // borderMode: "none", // 表格边框模式，none为无边框
  });
  const fieldsTypeMap: any = {};
  const getDetail = async () => {
    loading.value = true;
    const res = await detailTemplate(route.query.id as string);
    loading.value = false;
    templateDetails.value = res;
    tableDataOrigin.value = JSON.parse(res.config || "[]");
    tableData.value = JSON.parse(res.config || "[]").map((item: any) => {
      item.requiredName = item.required ? "必填" : "非必填";
      item.typexName = fieldsTypeMap[item.uiType];
      item.canOperate = item.canModify === 0;
      item.invisibleStatus = item.invisible === 1;
      item.isDisabled = item.disableModify ? "是" : "否";
      return item;
    });
    console.log(tableData.value, "tableData.value");
  };
  getDetail();
  const handleSearch = async () => {};

  const handleMoreAction = async (action: string, node: any) => {
    if (action === "edit") {
      console.log("node", node);
      dialogVisible.value = true;
      operate.value = "edit";
      selectedNode.value = deepCopy(node);
    } else if (action === "delete") {
      ElMessageBox.confirm("确定删除该字段?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      })
        .then(async () => {
          const dataCopy = deepCopy(tableDataOrigin.value);
          const index = dataCopy.findIndex((item) => item.sort === node.sort);
          dataCopy.splice(index, 1);
          const updateParams: BaseDataConfigEntityRes = {
            config: JSON.stringify(dataCopy),
            id: templateDetails.value.id,
            targetType: templateDetails.value.targetType as TargetType,
          };
          await updateTemplate(updateParams);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getDetail();
        })
        .catch(() => {});
    } else if (action === "invisibleStatus") {
      loading.value = true;
      const copyTableData = deepCopy(tableDataOrigin.value);
      const item = copyTableData.find((item) => item.sort === node.sort);
      if (item) {
        item.invisible = item.invisible === 1 ? 0 : 1;
      }
      const updateParams: BaseDataConfigEntityRes = {
        config: JSON.stringify(copyTableData),
        id: templateDetails.value.id,
        targetType: templateDetails.value.targetType as TargetType,
      };
      await updateTemplate(updateParams);
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      await getDetail();
    }
  };
  // 配置字段
  const currentFields = ref<DynamicField[]>([]);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const showFieldConfig = ref(false);

  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  // const addRecord = (newRecords: ProjectNode[]) => {
  //   tableData.value = [...newRecords];
  // };
  //
  // // 提供给所有子孙组件使用
  // provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  const handleAdd = () => {
    dialogVisible.value = true;
  };

  const handleCreateOrEdit = async (formData: any) => {
    console.log(formData);
    if (operate.value === "create") {
      const params = {
        canModify: 1,
        code: "", // 不管
        displayName: formData.displayName,
        uiType: formData.uiType,
        default: formData.default,
        sort: tableDataOrigin.value.length + 1,
        type: "VARCHAR", // 不管
        required: formData.required ? formData.required : false,
        invisible: 1,
        option: JSON.stringify(formData.option),
      };
      const tableDataList = JSON.parse(templateDetails.value.config || "[]");
      tableDataList.push(params);
      const updateParams: BaseDataConfigEntityRes = {
        config: JSON.stringify(tableDataList),
        id: templateDetails.value.id,
        targetType: templateDetails.value.targetType as TargetType,
      };
      await updateTemplate(updateParams);
      ElMessage({
        type: "success",
        message: "添加成功",
      });
      dialogVisible.value = false;
      await getDetail();
    } else if (operate.value === "edit") {
      const dataCopy = deepCopy(tableDataOrigin.value);
      const currentItem = dataCopy.find((item) => item.sort === formData.sort);
      if (currentItem) {
        currentItem.displayName = formData.displayName;
        currentItem.disableModify = formData.disableModify;
        currentItem.uiType = formData.uiType;
        currentItem.required = formData.required;
        currentItem.option = JSON.stringify(formData.option);
        const updateParams: BaseDataConfigEntityRes = {
          config: JSON.stringify(dataCopy),
          id: templateDetails.value.id,
          targetType: templateDetails.value.targetType as TargetType,
        };
        await updateTemplate(updateParams);
        ElMessage({
          type: "success",
          message: "编辑成功",
        });
        dialogVisible.value = false;
        await getDetail();
      }
    }
  };
  onMounted(async () => {
    const fieldDist = await dist.getDictData("sdm.global.defined.filedType");
    fieldDist.items.map((item) => {
      fieldsTypeMap[item.code] = item.displayName;
    });
  });
</script>

<style scoped lang="scss">
  .fieldTemplateDetail-container {
    display: flex;
    flex-direction: column;
    //padding: 16px;
    height: 100%;
    box-sizing: border-box;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 20px 10px 20px;
      .title {
        font-weight: 500;
        font-size: 18px;
        line-height: 22px;
      }
    }
    .content {
      padding: 8px 8px 0 8px;
      .alert {
        height: 32px;
        background: #fff3eb;
        display: flex;
        align-items: center;
        color: #5e5e5e;
        font-size: 14px;
        padding: 0 12px;
        margin-bottom: 14px;
      }
    }
  }
</style>
